package util;

import constant.ContentType;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import java.util.stream.Collectors;

public class HttpUtil {
    public static final TrustManager myX509TrustManager = new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }
    };

    /**
     * 发送 https请求
     *
     * @param requestUrl    路径
     * @param requestMethod 方式
     * @param output        数据
     * @return String
     * @throws IOException 异常
     */
    public static String httpsRequest(String requestUrl, String requestMethod, String output) throws IOException {
        URL url = new URL(requestUrl);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod(requestMethod);
        if (null != output) {
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(output.getBytes(StandardCharsets.UTF_8));
            outputStream.close();
        }
        // 从输入流读取返回内容
        InputStream inputStream = connection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String buffer = bufferedReader.lines().collect(Collectors.joining());
        bufferedReader.close();
        inputStreamReader.close();
        inputStream.close();
        connection.disconnect();
        return buffer;
    }

    /**
     * 是否是资源链接
     *
     * @param requestUrl 路径
     * @return true：资源 false：非资源
     * @throws Exception 异常
     */
    public static boolean isFileUrl(String requestUrl) throws Exception {
        URL uri = new URL(requestUrl);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
        if (requestUrl.startsWith("https")) {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[]{myX509TrustManager}, null);
            ((HttpsURLConnection) conn).setSSLSocketFactory(sslcontext.getSocketFactory());
        }
        conn.setRequestMethod("HEAD");
        conn.setRequestProperty("User-Agent", AgentUtil.get());
        int responseCode = conn.getResponseCode();
        if (responseCode < 200 || responseCode >= 300) {
            return false;
        }
        return !conn.getContentType().toLowerCase().contains(ContentType.TEXT_HTML);
    }

}
